/* eslint-disable */
import Vue from "vue";
import { Message } from "element-ui";
import axios from "axios";
import store from "@/store";
import loading from "./element"

const config = {
  // baseURL: process.env.VUE_APP_BASE_URL || process.env.apiUrl || "",
  baseURL: process.env.VUE_APP_BASE_URL ? "/api" : "",
  timeout: 60 * 1000,
  withCredentials: true // Check cross-site Access-Control
};


const _axios = axios.create(config);
let curMsg: any;

// Add a request interceptor
_axios.interceptors.request.use(
  function(config) {
    const time = new Date().getTime().toString();
    if(config.params){
      delEmpty(config.params);
      config.params.t = time;
    }
    if (config.data) {
      delEmpty(config.params);
      config.data.t = time;
    }
    return config;
  },
  function(error) {
    return Promise.reject(error);
  }
);

function delEmpty(data){
  if(data){
    for (const item in data) {
      if (data.hasOwnProperty(item)) {
        const val = data[item];
        if ((val == null || val == "null" || val == "") && val !== 0) {
          delete data[item];
        }
      }
    }
  }
}

// Add a response interceptor
_axios.interceptors.response.use(
  function(response) {
    if (!response.data.message) {
      return { success: true, data: response.data };
    }
    return response.data;
  },
  function(error) {
    return Promise.reject(error);
  }
);

function post(url, data = {}, noMsg, noLoading) {
  return new Promise((resolve, reject) => {
    if(!noLoading){
      loading.start();
    }
    _axios.post(url, data).then(
      (response: any) => {
        if(!noLoading){
          loading.stop();
        }
        if (response.success) {
          if (response.message) {
            showMessage("success", response.message, false, noMsg);
            resolve(true);
          } else {
            resolve(response.data);
          }
        } else {
          if (response.message == "session timeout") {
            store.commit("loginOut");
          }
          if (response.message == "no permission") {
            response.message = "您暂无权访问，请联系管理员添加";
          }
          if (response.message.indexOf("no permission for ") == 0) {
            response.message = "此权限尚未开放，请勿越权访问";
          }
          showMessage("error", response.message, false, noMsg);
          if (response.error != null) {
            console.log(response.error);
          }
          resolve(response.data);
        }
      },
      err => {
        if(!noLoading){
          loading.stop();
        }
        showMessage("error", "后台连接失败，网络异常！", false, noMsg);
        reject(err);
      }
    );
  });
}

function get(url, data = {}, noMsg, noLoading) {
  return new Promise((resolve, reject) => {
    if(!noLoading){
      loading.start();
    }
    _axios.get(url, {params:data}).then(
      (response: any) => {
        if(!noLoading){
          loading.stop();
        }
        if (response.success) {
          if (response.message) {
            showMessage("success", response.message, false, noMsg);
            resolve(true);
          } else {
            resolve(response.data);
          }
        } else {
          if (response.message == "session timeout") {
            store.commit("loginOut");
          }
          if (response.message == "no permission") {
            response.message = "您暂无权访问，请联系管理员添加";
          }
          if (response.message.indexOf("no permission for ") == 0) {
            response.message = "此权限尚未开放，请勿越权访问";
          }
          showMessage("error", response.message, false, noMsg);
          console.log(response.error);
          resolve(false);
        }
      },
      err => {
        if(!noLoading){
          loading.stop();
        }
        showMessage("error", "后台连接失败，网络异常！", false, noMsg);
        reject(err);
      }
    );
  });
}

function download(fileName, url, data = {}, callBack) {
  loading.start();
  _axios({
    method: "post",
    url: url, // 请求地址
    data: data, // 参数
    responseType: "blob" // 表明返回服务器返回的数据类型
  }).then(
    response => {
      loading.stop();
      const data = response.data;
      const reader = new FileReader() as any;
      reader.readAsText(data);
      reader.onload = function() {
        try {
          const result = JSON.parse(reader.result);
          if (typeof result === "object") {
            showMessage("error", result.message, false, false);
            if (callBack != null) {
              callBack(false);
            }
            return;
          }
        } catch (err) {}
        const blob = new Blob([data], {
          type: "application/vnd.ms-excel"
        });
        if (window.navigator.msSaveOrOpenBlob) {
          navigator.msSaveBlob(blob, fileName);
        } else {
          const link = document.createElement("a");
          link.href = window.URL.createObjectURL(blob);
          link.download = fileName;
          link.click();
          window.URL.revokeObjectURL(link.href);
        }
        if (callBack != null) {
          callBack(true);
        }
      };
    },
    err => {
      loading.stop();
      showMessage("error", "下载失败，网络异常！", false, false);
      if (callBack != null) {
        callBack(false);
      }
    }
  );
}

function showMessage(type, info, unClose, noMsg) {
  const vue = Vue as any;
  if (noMsg) {
    return;
  }
  if (curMsg != null) {
    curMsg.close();
  }
  const tmp = Message({
    type: type,
    showClose: true,
    message: info,
    duration: 3000
  });
  if (!unClose) {
    curMsg = tmp;
  }
}

function showNotify(type, title, message, position) {
  const vue = Vue as any;
  if (position == null) {
    position = "top-right";
  }
  vue.$notify({
    title: title,
    type: type,
    message: message,
    position: position,
    duration: 0
  });
}

Vue.prototype.$post = post;
Vue.prototype.$get = get;
Vue.prototype.$download = download;
Vue.prototype.$showMessage = showMessage;
Vue.prototype.$showNotify = showNotify;

export default {
    post,
    get,
    download,
    showMessage,
    showNotify
}
